package util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sections.ISection;
import sections.ISection.Section;

public class ListenerManager implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -6763847971192349426L;
	Map<ISection.Section, List<ISectionListener>> fListeners;

	public ListenerManager()
	{
		fListeners = new HashMap<ISection.Section, List<ISectionListener>>();

		fListeners.put(Section.TABLE, new ArrayList<ISectionListener>());
		fListeners.put(Section.TYPE, new ArrayList<ISectionListener>());
		fListeners.put(Section.REF_TYPE, new ArrayList<ISectionListener>());
		fListeners.put(Section.REL, new ArrayList<ISectionListener>());
		fListeners.put(Section.REL_TO_REL, new ArrayList<ISectionListener>());
	}

	public void registerListener(Section section, ISectionListener listener)
	{
		List<ISectionListener> listenerList = fListeners.get(section);

		if (listenerList == null)
		{
			listenerList = new ArrayList<ISectionListener>();
		}

		if (!listenerList.contains(listener))
		{
			listenerList.add(listener);
		}

		fListeners.put(section, listenerList);
	}

	public void notifyListeners(ISection.Section section)
	{
		List<ISectionListener> listenerList = fListeners.get(section);

		if (listenerList == null)
		{
			return;
		}

		for (ISectionListener listener : listenerList)
		{
			listener.acceptChange(section);
		}
	}

	public void unregisterListener(Section section, ISectionListener listener)
	{
		List<ISectionListener> listenerList = fListeners.get(section);

		if (listenerList == null)
		{
			return;
		}

		listenerList.remove(listener);
	}
}
